import { CloseCircleOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, message } from 'antd';
import { memo, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { HOME_URL } from '../../routers/AuthRouter';
import { userLogin } from '../../service/api/user';
import { ApiUserLogin } from '../../service/api/user/Type';
import { updateToken, updateUserInfo, useAppDispatch } from '../../store';

const inteFormValue: ApiUserLogin = {
    username: 'admin',
    password: '123456',
};

const LoginForm = () => {
    const navigate = useNavigate();
    const [form] = Form.useForm<ApiUserLogin>();
    const [loading, setLoading] = useState<boolean>(false);
    const dispatch = useAppDispatch();

    // 登录
    const onFinish = async (loginForm: ApiUserLogin) => {
        try {
            setLoading(true);
            const data = await userLogin(loginForm);
            dispatch(updateToken(data.token));
            dispatch(updateUserInfo(data.info));
            message.success('登录成功！');
            navigate(HOME_URL);
        } finally {
            setLoading(false);
        }
    };

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };

    useEffect(() => {
        form.setFieldsValue(inteFormValue);
    }, [form]);

    return (
        <Form
            form={form}
            name="basic"
            labelCol={{ span: 5 }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            size="large"
            autoComplete="off"
        >
            <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                <Input placeholder="用户名：admin / user" prefix={<UserOutlined />} />
            </Form.Item>
            <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
                <Input.Password
                    autoComplete="new-password"
                    placeholder="密码：123456"
                    prefix={<LockOutlined />}
                />
            </Form.Item>
            <Form.Item className="login-btn">
                <Button
                    onClick={() => {
                        form.resetFields();
                    }}
                    icon={<CloseCircleOutlined />}
                >
                    重置
                </Button>
                <Button type="primary" htmlType="submit" loading={loading} icon={<UserOutlined />}>
                    登录
                </Button>
            </Form.Item>
        </Form>
    );
};

export default memo(LoginForm);
